package com.wfh.rpc.loadbalancer;

import com.wfh.rpc.model.ServiceModelInfo;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Title: ConsistentHashLoadBalancer
 * @Author wangfenghuan
 * @Package com.wfh.rpc.loadbalancer
 * @Date 2025/10/16 21:05
 * @description: 一致性hash负载均衡器
 */
public class ConsistentHashLoadBalancer implements LoadBalancer{

    /**
     * 一致性哈希环
     */
    private final TreeMap<Integer, ServiceModelInfo> virtualNodes = new TreeMap<>();

    /**
     * 虚拟节点数
     */
    private static final int VIRTUAL_NODE_NUM = 100;

    @Override
    public ServiceModelInfo select(Map<String, Object> requestParams, List<ServiceModelInfo> serviceModelInfoList) {

        if (serviceModelInfoList.isEmpty()){
            return null;
        }
        // 构建虚拟节点环
        for (ServiceModelInfo serviceModelInfo : serviceModelInfoList) {
            for (int i = 0; i < VIRTUAL_NODE_NUM; ++i){
                int hash = getHash(serviceModelInfo.getServiceAddress() + "#" + i);
                virtualNodes.put(hash, serviceModelInfo);
            }
        }

        return null;
    }

    /**
     * 哈希算法
     * @param s
     * @return
     */
    private int getHash(String s) {
        return s.hashCode();
    }
}
